<?php

namespace App\Library;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Cookie;

class SwooleHandler {
    public function __construct() {
    }

    public static $user = [];

    public function onRequest($request, $response) {
        $path_info = $request->server['path_info']; //url请求地址
        $root_path = dirname(dirname(__DIR__ . '/')); //静态根目录
        if(is_file($path_info)) {
            $extension = pathinfo($path_info, PATHINFO_EXTENSION);
            $response->header('Content-Type', (new Mines())->type()[$extension]);
            $result = file_get_contents($path_info);
        } else {
            $router = ltrim($path_info, '/');
            view()->share('root_path', $root_path);
            if(empty($router)) {
                $result = view("swoole.index");
            } else {
                $isExists = view()->exists("swoole.{$router}");
                if($isExists) {
                    $result = view("swoole.{$router}");
                } else {
                    $result = view("swoole.503");
                }
            }
        }
        $response->end($result);
    }

    public function onOpen($server, $request) {
        echo "进入{$request->fd} \n";
        self::$user[$request->fd] = $request->fd;
        //        echo "server: handshake success with fd{$request->fd}\n";
        $server->push($request->fd, '连接成功');
    }

    public function onMessage($server, $frame) {
        $data = json_decode($frame->data);
        $type='msg'; //消息类型
        if(isset($data->fun) && $data->fun == 'auth') {
            self::$user[$frame->fd] = $data->name;
            $frame->data = '进入聊天室';
            $type='into';//进入类型
        }
        Cache::forever('Chat', self::$user);
        foreach(self::$user as $key => $value) {
            $server->push($key, json_encode(['name' => self::$user[$frame->fd], 'data' => $frame->data,'type'=>$type]));
        }
    }

    /**
     * 初始化服务时 创建的对象可以在进程生命周期
     * @param $server
     * @param $worker_id
     */
    public function onWorkerStart($server, $worker_id) {
    }

    public function onClose($server, $fd) {
        unset(self::$user[$fd]);
    }

    /**
     *  用户绑定
     */
    public function userBind() {
    }

}